package com.online.shopping.service.impl;

import com.alibaba.fastjson.JSON;
import com.online.shopping.mapper.TbSpecificationMapper;
import com.online.shopping.mapper.TbSpecificationOptionMapper;
import com.online.shopping.mapper.TbTypeTemplateMapper;
import com.online.shopping.pojo.TbSpecificationOption;
import com.online.shopping.pojo.TbSpecificationOptionExample;
import com.online.shopping.pojo.TbTypeTemplate;
import com.online.shopping.service.TypeTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class TypeTemplateServiceImpl implements TypeTemplateService {

	@Autowired
	private TbTypeTemplateMapper typeTemplateMapper;

	@Autowired
	private TbSpecificationMapper specificationMapper;

	@Autowired
	private TbSpecificationOptionMapper specificationOptionMapper;

	@Override
	public List<TbTypeTemplate> findAllTypeTemplate() {
		return typeTemplateMapper.selectByExample(null);
	}

	@Override
	public TbTypeTemplate findTypeTemplateById(Long id) {
		return typeTemplateMapper.selectByPrimaryKey(id);
	}

	@Override
	public void add(TbTypeTemplate typeTemplate) {
		typeTemplateMapper.insert(typeTemplate);
	}

	@Override
	public void update(TbTypeTemplate typeTemplate) {
		typeTemplateMapper.updateByPrimaryKey(typeTemplate);
	}

	@Override
	public void delete(Long[] ids) {
		for(Long id : ids){
			typeTemplateMapper.deleteByPrimaryKey(id);
		}
	}

	@Override
	public List<Map> findSpecList(Long id) {
		// 根据ID查询到模板对象
		TbTypeTemplate typeTemplate = typeTemplateMapper.selectByPrimaryKey(id);

		// 获得规格的数据spec_ids
		String specIds = typeTemplate.getSpecIds();     // [{"id":27,"text":"网络"},{"id":32,"text":"机身内存"}]

		// 将specIds的字符串转成JSON的List<Map>
		List<Map> list = JSON.parseArray(specIds, Map.class);

		// 获得每条记录
		for (Map map : list) {
			// 根据规格的ID，查询规格选项的数据
			// 设置查询条件
			TbSpecificationOptionExample example = new TbSpecificationOptionExample();
			TbSpecificationOptionExample.Criteria criteria = example.createCriteria();

			criteria.andSpecIdEqualTo(new Long((Integer)map.get("id")));
			List<TbSpecificationOption> specOptionList = specificationOptionMapper.selectByExample(example);

			// 查询tb_specification_oprion表，加载option_name字段，然后封装到map中
			map.put("options", specOptionList);     // {"id":27,"text":"网络",options:[{id：xxx,optionName:移动2G}]}
		}
		return list;
	}
}
